<template>
  <div id="login-app">
    <h1>登录页面</h1>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="用户名">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input
          v-model="form.password"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import store from '@/store'
export default {
  name: 'LoginApp',
  data() {
    return {
      form: {
        username: 'ash',
        password: '123'
      }
    }
  },
  created() {
    //methods和data已经初始化,常用于操作数据，发起ajax请求
    if (store.state.token) {
      window.location.href = '/'
    }
  },
  methods: {
    onSubmit() {
      console.log('登录：', this.form)
      store
        .dispatch('loginAsync', this.form)
        .then(res => {
          if (res.success) {
            console.log('登陆成功')
            // 跳转到管理页面
            this.$message({
              message: '登录成功',
              type: 'success'
            })
            window.location.href = '/'
          }
        })
        .catch(err => {
          console.log(err)
          this.$message({
            message: '用户名或密码错误',
            type: 'error'
          })
        })
    }
  }
}
</script>

<style lang="scss" scoped>
h1 {
  text-align: center;
}
</style>
